package com.hibikiluler.javalearning.controller;

import com.hibikiluler.javalearning.service.SysUserService;
import com.hibikiluler.javalearning.util.RedisUtils;
import com.hibikiluler.javalearning.util.Result;
import com.hibikiluler.javalearning.util.SecurityUtils;
import com.hibikiluler.javalearning.vo.Loginvo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;


/**
 *  登录
 *  退出
 *  获取当前用户的基本信息
 *  相关的接口
 */
@Slf4j
@RestController
@Api(value = "登录控制器接口")
@RequestMapping("/user")
public class LoginController {

    @Autowired
    private SysUserService userService;

    @Autowired
    private RedisUtils redisUtils;

    @ApiOperation(value = "登录接口")
    @PostMapping("/login")
    public Result login(@RequestBody Loginvo loginvo){
        return userService.login(loginvo);
    }

    @ApiOperation(value = "短信登录")
    @PostMapping("/sms/login")
    public Result smsLogin(@RequestBody Loginvo loginVo) {
        return userService.login(loginVo);
    }

    @ApiOperation(value = "获取用户基本信息")
    @GetMapping("/getInfo")
    //发给前端的用户信息SecurityUtil.getUser()
    public  Result getUserInfo(){
//        String str2 = new String(SecurityUtils.getUser().toString());
//        log.info(str2);   //用于检查传给前端的东西
        return Result.success("获取用户信息成功", SecurityUtils.getUser());
    };

    @ApiOperation(value = "用户退出登录")
    @GetMapping("/loginout")
    public Result loginout(){
        // 清除缓存
        redisUtils.delKey("userInfo_" + SecurityUtils.getUsername());
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (null != authentication){
            SecurityContextHolder.getContext().setAuthentication(null);
        }
        return Result.success("退出成功");
    }
}
